/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package skytestarmor;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;
import org.apache.log4j.Logger;
import ru.jSkyRoom.bridge.ModBridge;
import ru.jSkyRoom.factory.BridgeFactory;
import ru.jSkyRoom.factory.FilterFactory;
import ru.jSkyRoom.filter.Filter;
import ru.jSkyRoom.interfaces.JSkyMod;
import ru.jSkyRoom.interfaces.major.Armor;
import ru.jSkyRoom.interfaces.major.Enchantment;
import ru.jSkyRoom.interfaces.major.Keyword;
import ru.jSkyRoom.support.GrupTypeBuilder;
import ru.jSkyRoom.support.SyntaticModBuilder;
import skyproc.ARMO;
import skyproc.ENCH;
import skyproc.KYWD;
import skyproc.Mod;
import skyproc.SPGlobal;
import skyproc.SPImporter;
import skyproc.exceptions.NotFound;
import skyproc.gui.SPDefaultGUI;

/**
 *
 * @author Dima
 */
public class SimpleSkyTestArmor {

    private static SPDefaultGUI gui;
    private static final Logger logger = Logger.getLogger(GeneratorOfKeywordEnchantmentsLinks.class.getName());

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        File dir = new File(System.getProperty("user.dir"));
        String ddhjj = new File(".").getAbsolutePath();



        BufferedReader myfile;
        try {
            myfile = new BufferedReader(new FileReader(".\\patches.txt"));
            String patchDir = myfile.readLine();
            String workDir = null;
            if (patchDir != null) {
                workDir = myfile.readLine();
            } else {
                logger.error("Файл 'patches.txt' пуст. ");
            }

            if (workDir != null) {
                if (!workDir.endsWith("\\")) {
                    workDir.concat("\\");
                }
                if (!patchDir.endsWith("\\")) {
                    patchDir.concat("\\");
                }
                Boolean mayCreate = true;
                if (!patchDir.endsWith("Data\\")) {
                    mayCreate = false;
                    logger.error("В файле 'patches.txt' путь в первой строке должен заканчиваться на 'Data\\' ");
                }
                if (!workDir.endsWith("KR_settings\\")) {
                    logger.error("В файле 'patches.txt' путь во второй строке должен заканчиваться на 'KR_settings\\' ");
                    mayCreate = false;
                }

                if (mayCreate) {
                    preperaForPatch(workDir, patchDir);
                }
            } else {
                logger.error("В файле 'patches.txt' нет второй строки с путем к папке конфигураций KR_settings''. ");
            }
        } catch (FileNotFoundException ex) {
            logger.error("Файл 'patches.txt' не найден", ex);
        } catch (IOException ex) {
            logger.error("Ошибка ввода вывода в файле 'patches.txt' ", ex);
        }



    }

    private static void preperaForPatch(String workDir, String patchDir) {
        SPGlobal.createGlobalLog();
        try {
            Mod patch = new Mod("KR_EnchArmorSklad_LB", false);
            SPGlobal.setGlobalPatch(patch);
            SPGlobal.pathToData = patchDir;

            gui = new SPDefaultGUI("KR_EnchArmorSklad_LB", "KR_EnchArmorSklad_LB");

            SPImporter importer = new SPImporter();

            GrupTypeBuilder grupTypeBuilder = new GrupTypeBuilder();
            grupTypeBuilder.Armor().Enchantment().FormList().Keyword().LeveledItemList();
            SPImporter.importActiveMods(grupTypeBuilder.build());
            SPImporter.getActiveModList();

            useEnch(workDir);

            patch.setAuthor("Kepper");
            patch.export();

            gui.finished();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void useEnch(String workDir) throws NotFound, IOException {
        FileWriter txtFile2;
        PrintWriter txtPrint2;


        SyntaticModBuilder syntaticModBuilder = new SyntaticModBuilder();
        syntaticModBuilder.add("Skyrim.esm", "Update.esm", "Dragonborn.esm", "Dawnguard.esm", "LB_ArmorPack.esm");
        //syntaticModBuilder.add("Kepper_Radiant_LB.esp", "KR_WeaponPack.esp");
        //syntaticModBuilder.add("Kepper_Radiant_LB_test.esp", "KR_WeaponPack.esp");
        syntaticModBuilder.add("Kepper_Radiant_LB.esp", "KR_WeaponPack.esp");
        Mod merger = ((ModBridge) syntaticModBuilder.build()).getRawObject();

        SyntaticModBuilder syntaticModBuilder2 = new SyntaticModBuilder();
        //syntaticModBuilder2.add("Kepper_Radiant_LB.esp", "KR_WeaponPack.esp");
        //syntaticModBuilder2.add("Kepper_Radiant_LB_test.esp", "KR_WeaponPack.esp");
        syntaticModBuilder2.add("Kepper_Radiant_LB.esp", "KR_WeaponPack.esp");
        Mod mainModKR = ((ModBridge) syntaticModBuilder2.build()).getRawObject();

        /*
         GeneralFactory generalFactory = new GeneralFactory(merger);
         SkyProcFactory skyProcFactory = new SkyProcFactory(generalFactory);
         ru.jSky.skyProc.linkLoader.LinkerFactory linkerFactory = skyProcFactory.createLinkerFactory();
         ru.jSky.skyProc.linkLoader.KeyWordEnchantmentsLinker keyWordEnchantmentsLinker = linkerFactory.createKeyWordEnchantmentsLinker(loadBaseEnchantment(merger));
         Map<KYWD, ArrayList<ENCH>> keyWordEnchantmentsLinks = keyWordEnchantmentsLinker.getLinks();*/
        /*
         RecordFinderFactory recordFinderFactory = generalFactory.createRecordFinderFactory();
         RecordFinder<KYWD> recordProducer = recordFinderFactory.createKYWD();
         KYWD keyWord = recordProducer.find("0006C0EC", "Skyrim.esm");*/

        //String tmp_str = Kepper_Radiant_LB_esp.getArmors().get("Ench_LB_Bat_Cuirass01_Conjuration01").getForm().getTitle(); //FormID

        //NamesOfEnchments namesOfEnchments = new NamesOfEnchments(keyWordEnchantmentsLinks);
        JSkyMod jsMerger = BridgeFactory.create().createBridge(merger);
        GeneratorOfKeywordEnchantmentsLinks generator = new GeneratorOfKeywordEnchantmentsLinks(jsMerger, workDir);
        Map<Keyword, Collection<Enchantment>> keywordEnchantmentsLinks = generator.getKeywordEnchantmentsLinks();
        Collection<Armor> armorList = generator.getArmorList();

        NamesOfEnchments namesOfEnchments = new NamesOfEnchments(keywordEnchantmentsLinks, jsMerger);



        /*
         for (KYWD keyword : keywordEnchantmentsLinks.keySet()) {
         // kewordFormID


         try {
         txtFile2 = new FileWriter("D:\\KR_settings\\Enchantments\\" + keyword.getEDID() + ".txt");
         //txtFile2 = new FileWriter(".\\Enchantments\\" + keyword.getEDID() + ".txt");
         txtPrint2 = new PrintWriter(txtFile2);

         ArrayList<ENCH> enchantmentsList = keywordEnchantmentsLinks.get(keyword);
         for (ENCH record : keywordEnchantmentsLinks.get(keyword)) {
         txtPrint2.println(record.getEDID());

         }

         txtFile2.close();
         } catch (IOException ex) {
         Logger.getLogger(NamesOfEnchments.class.getName()).log(Level.SEVERE, null, ex);
         }
         }
         */
        /*
         String nameLeveledItems;
         LVLI leveledItems;

         nameLeveledItems = "LBench_RobesAlteration_01";  // LBench_RobesAlteration_03
         leveledItems = (LVLI) SPGlobal.getGlobalPatch().getLeveledItems().get(nameLeveledItems);
         if (leveledItems == null) {
         leveledItems = (LVLI) merger.getLeveledItems().get(nameLeveledItems);
         if (leveledItems == null) {
         int hjh = 0;
         // leveledItems = (LVLI) SPGlobal.getGlobalPatch().makeCopy(merger.getLeveledItems().get("LItem_LB__Gloves"), nameLeveledItems);
         }
         }

         nameLeveledItems = "LItemEnchCircletAlchemy_LB_KR";  // LBench_RobesAlteration_03
         leveledItems = (LVLI) SPGlobal.getGlobalPatch().getLeveledItems().get(nameLeveledItems);
         if (leveledItems == null) {
         leveledItems = (LVLI) merger.getLeveledItems().get(nameLeveledItems);
         if (leveledItems == null) {
         int hjh = 0;
         // leveledItems = (LVLI) SPGlobal.getGlobalPatch().makeCopy(merger.getLeveledItems().get("LItem_LB__Gloves"), nameLeveledItems);
         }
         }

         */

        ARMO tmpArmor;
        KYWD keyword;
        /*
         tmpArmor = (ARMO) merger.getArmors().get("LB_Valkyrie_Cuirass");
         keyword = (KYWD) merger.getKeywords().get("ArmorCuirass");
         namesOfEnchments.createEnchmentArmorByKeyword(tmpArmor, merger, keyword);
         tmpArmor = (ARMO) merger.getArmors().get("LB_DivineEbony_CuirassChain");
         namesOfEnchments.createEnchmentArmorByKeyword(tmpArmor, merger, keyword);
         tmpArmor = (ARMO) merger.getArmors().get("LB_DivineEbony_CuirassNaked");
         namesOfEnchments.createEnchmentArmorByKeyword(tmpArmor, merger, keyword);
         tmpArmor = (ARMO) merger.getArmors().get("LB_DwarvenFury_Cuirass");
         namesOfEnchments.createEnchmentArmorByKeyword(tmpArmor, merger, keyword);

         keyword = (KYWD) merger.getKeywords().get("ArmorHelmet");
         tmpArmor = (ARMO) merger.getArmors().get("LB_DwarvenFury_Helmet");
         namesOfEnchments.createEnchmentArmorByKeyword(tmpArmor, merger, keyword);



         keyword = (KYWD) merger.getKeywords().get("ClothingBody");
         tmpArmor = (ARMO) merger.getArmors().get("LB_ClothesYarl_Blue1_Corset01");
         namesOfEnchments.createEnchmentArmorByKeyword(tmpArmor, merger, keyword);


         keyword = (KYWD) merger.getKeywords().get("ClothingCirclet");
         tmpArmor = (ARMO) merger.getArmors().get("LB_SilverLight_Circlet");
         namesOfEnchments.createEnchmentArmorByKeyword(tmpArmor, merger, keyword);


         keyword = (KYWD) merger.getKeywords().get("ClothingNecklace");
         tmpArmor = (ARMO) merger.getArmors().get("LB_Divine_Necklace");
         namesOfEnchments.createEnchmentArmorByKeyword(tmpArmor, merger, keyword);
         */

        /*
         tmpArmor = (ARMO) merger.getArmors().get("LB_DivineEbony_CuirassNaked");
         namesOfEnchments.createEnchmentArmors(tmpArmor, merger);

         tmpArmor = (ARMO) merger.getArmors().get("LB_DwarvenFury_Helmet");
         namesOfEnchments.createEnchmentArmors(tmpArmor, merger);

         tmpArmor = (ARMO) merger.getArmors().get("LB_ClothesYarl_Blue1_Corset01");
         namesOfEnchments.createEnchmentArmors(tmpArmor, merger);

         tmpArmor = (ARMO) merger.getArmors().get("LB_SilverLight_Circlet");
         namesOfEnchments.createEnchmentArmors(tmpArmor, merger);

         tmpArmor = (ARMO) merger.getArmors().get("LB_Divine_Necklace");
         namesOfEnchments.createEnchmentArmors(tmpArmor, merger);
         */
        /*
         tmpArmor = (ARMO) merger.getArmors().get("LB_Alina_Gloves");
         namesOfEnchments.createEnchmentArmors(tmpArmor, merger);
         */



        // txtFile2 = new FileWriter("C:\\Steam\\SteamApps\\common\\Skyrim\\Data\\Armors_Test.txt");
        //  txtPrint2 = new PrintWriter(txtFile2);

        try {



            for (Armor armor : armorList) {
                /*
                 Boolean isLightArmor = armor.getKeywordSet().getKeywordRefs().contains(merger.getKeywords().get("ArmorLight").getForm());
                 Boolean isHeavyArmor = armor.getKeywordSet().getKeywordRefs().contains(merger.getKeywords().get("ArmorHeavy").getForm());
                 Boolean isHelmet = armor.getKeywordSet().getKeywordRefs().contains(merger.getKeywords().get("ArmorHelmet").getForm());
                 if (armor.getEDID().equals("LB_DwarvenFury_Helmet")) {
                 isHelmet = armor.getKeywordSet().getKeywordRefs().contains(merger.getKeywords().get("ArmorHelmet").getForm());

                 }
                 if ((isLightArmor || isHeavyArmor) && !isHelmet) {
                 txtPrint2.println(armor.getEDID());
                 namesOfEnchments.createEnchmentArmors(armor, merger);
                 }
                 */
                //txtPrint2.println(armor.getEDID());
                namesOfEnchments.createEnchmentArmors(armor, jsMerger);

            }
        } catch (Exception e) {
            e.printStackTrace();
            //    LDebug.wrapUp();
        }


        //txtFile2.close();


        LeveledOutfits outfitsCreator = new LeveledOutfits(jsMerger, workDir);




        //tmpArmor = (ARMO) merger.getArmors().get("LB_Valkyrie_Gloves");
        //namesOfEnchments.createEnchmentArmors(tmpArmor, merger);

        //tmpArmor = (ARMO) merger.getArmors().get("LB_Valkyrie_Boots");
        //namesOfEnchments.createEnchmentArmors(tmpArmor, merger);

        //String tmp_str = merger.getArmors().get("Ench_LB_Bat_Cuirass01_Conjuration01").getEDID(); //EditorID



        /*
         ARMO armor = (ARMO) kepper_Radiant_LB_esp.getArmors().get("Ench_LB_Bat_Cuirass01_Conjuration01");

         for (FormID keword : armor.getKeywordSet().getKeywordRefs() ){


         }
         */
        /*
         Map<String, ENCH>[] returnMaps = getVanilaArmorRobeEnbhantments(kepper_Radiant_LB_esp);
         Map<String, ENCH> enchArmorListForm = returnMaps[0];
         Map<String, ENCH> enchRobesListForm = returnMaps[1];

         String editorId;
         for (ARMO armor : kepper_Radiant_LB_esp.getArmors()) {
         editorId = armor.getEDID();
         editorId
         }
         */
        //     EnbhantmentsBank enbhantmentsBank = new EnbhantmentsBank(kepper_Radiant_LB_esp);
/*
         txtFile2 = new FileWriter("C:\\Steam\\SteamApps\\common\\Skyrim\\Data\\Armors.txt");
         txtPrint2 = new PrintWriter(txtFile2);
         for (ARMO armo : mainModKR.getArmors()) {
         if ((armo.getEDID().startsWith("LB_"))
         && !armo.getEDID().contains("Legend")
         && !armo.getEDID().contains("__")
         && !armo.getEDID().contains("NoPlayer")
         && !armo.getEDID().contains("Skirt")
         && !armo.getEDID().equals("LB_Bat_BootsArm")
         && !armo.getEDID().equals("LB_Valkyrie_Corset")
         && !armo.getEDID().equals("LB_Huntress_ArmGloves")
         && !armo.getEDID().equals("LB_Huntress_Stocking")
         && !armo.getEDID().equals("LB_Valkyrie_Panties")
         && !armo.getEDID().equals("LB_Valkyrie_ShoulderLight")
         && !armo.getEDID().equals("LB_Valkyrie_Shoulder")
         && !armo.getEDID().equals("LB_Demon_RoyalLordVampire")
         && !armo.getEDID().equals("LB_Frostbite_Leg")
         && !armo.getEDID().equals("LB_Frostbite_Shoulders")
         && !armo.getEDID().equals("LB_LuxLucius_Leg")
         && !armo.getEDID().equals("LB_LuxLucius_Shoulder")
         && !armo.getEDID().equals("LB_ManduHeavy_Shoulders")
         && !armo.getEDID().equals("LB_ValkyrieNew_Panties")
         && !armo.getEDID().startsWith("LB_Body_")
         //&& !armo.getEDID().startsWith("LB_BesBikini")
         //&& !armo.getEDID().startsWith("LB_C1_Bikini")
         && !armo.getEDID().startsWith("LB_Clothes")
         && !armo.getEDID().startsWith("LB_LustrVampire")
         && !armo.getEDID().startsWith("LB_LuxCloth")
         && !armo.getEDID().startsWith("LB_MoragTong")
         && !armo.getEDID().startsWith("LB_Nocturnal")
         && !armo.getEDID().startsWith("LB_SantaBaby") //&& !armo.getEDID().startsWith("LB_Sexy_Body")
         ) {


         txtPrint2.println("armorList.add((ARMO) patc.getArmors().get(\"" + armo.getEDID() + "\"));");
         //txtPrint2.println(armo.getEDID());
         }
         }
         txtFile2.close();
         */
        /*
         EnbhantmentsBank enbhantmentsBank = new EnbhantmentsBank(merger);

         FormID enchID = new FormID("0006C0EC", "Skyrim.esm");
         Map<String, ENCH> res = enbhantmentsBank.getEnchListByKeyword(enchID);

         FileWriter txtFile;
         PrintWriter txtPrint;
         FileWriter txtFile2;
         PrintWriter txtPrint2;
         txtFile2 = new FileWriter("C:\\Steam\\SteamApps\\common\\Skyrim\\Data\\keyword.txt");
         txtPrint2 = new PrintWriter(txtFile2);
         for (KYWD keyword : keyWordEnchantmentsLinks.keySet()) {
         txtPrint2.println(keyword.getEDID() + " " + keyword.getForm());

         txtFile = new FileWriter("C:\\Steam\\SteamApps\\common\\Skyrim\\Data\\" + keyword.getEDID() + ".txt");
         txtPrint = new PrintWriter(txtFile);



         txtPrint.println("private void fullKeywordEnchantmentsLinks_" + keyword.getEDID() + "(Mod patc) {");
         txtPrint.println("KYWD keyword;");
         txtPrint.println("ArrayList<ENCH> enchantmentsList;");


         txtPrint.println("keyword = (KYWD) patc.getKeywords().get(\"" + keyword.getEDID() + "\");");
         txtPrint.println("enchantmentsList = new ArrayList<ENCH>();");
         for (ENCH enchment : keyWordEnchantmentsLinks.get(keyword)) {
         String edIDname = enchment.getEDID();
         txtPrint.println("enchantmentsList.add((ENCH) patc.getEnchantments().get(\"" + edIDname + "\"));");
         //txtFile.write(edIDname+"\n");



         }
         txtPrint.println("}");
         txtFile.close();

         }
         txtFile2.close();




         String tmp_srtt = "jjkjk";
         /*
         Mod armor_list = new Mod("armor_listr", false);
         for ( ) {
         armor_list.addAsOverrides(SPGlobal.getDB());
         }
         //FormID enchID = new FormID("000F6905", "Skyrim.esm");
         for (ARMO armor : armor_list.getArmors()) {
         armor.getFormStr().indexOf("Legeng");
         armor.setEnchantment(enchID);
         patch.addRecord(armor);

         }
         */
    }
}
